//
//  HJVideoPlayerController.m
//  HJVideoPlayer
//
//  Created by WHJ on 2016/12/8.
//  Copyright © 2016年 WHJ. All rights reserved.
//

#import "HJVideoPlayerController.h"
#import "HJVideoBottomView.h"
#import "HJVideoPlayManager.h"
#import "HJVideoUIManager.h"
#import "HJPlayerView.h"
#import <MediaPlayer/MediaPlayer.h>
#import "HJViewFactory.h"
#import "HJVideoMaskView.h"
#import "HJVideoPlayerHeader.h"
#import "AppDelegate+HJVideoRotation.h"
#import "HJVideoPlayerUtil.h"
#import "UIDevice+HJVideoRotation.h"
#import "HJVideoConst.h"
#import "HJVideoPlayTimeRecord.h"

#import "YYEChapterModel.h"


#import <MediaPlayer/MediaPlayer.h>
//#import "AliyunPlayMessageShowView.h"
//#import "UIView+Layout.h"

typedef NS_ENUM(NSUInteger, MoveDirection) {
    MoveDirection_none = 0,
    MoveDirection_up,
    MoveDirection_down,
    MoveDirection_left,
    MoveDirection_right
};



#define BUTTONTAG  5001

@interface HJVideoPlayerController ()<AliyunVodPlayerDelegate>{
    //代表进度条是否可以更新
    BOOL  mProgressCanUpdate;
}



@property (nonatomic ,strong) HJVideoMaskView * maskView;


@property (nonatomic ,strong) HJVideoBottomView * bottomView;

@property (nonatomic ,assign) CGRect originFrame;

@property (nonatomic, assign) BOOL isFullScreen;

//@property (nonatomic, strong) HJPlayerView *playerView;
@property(nonatomic ,strong) UIView *playerView;

@property (nonatomic, assign) VideoPlayerStatus playStatus;

@property (nonatomic, assign) VideoPlayerStatus prePlayStatus;
/** 隐藏时间 */
@property (nonatomic, assign) NSInteger secondsForBottom;
/** 开始移动 */
@property (nonatomic, assign) CGPoint startPoint;
/** 移动方向 */
@property (nonatomic, assign) MoveDirection moveDirection;
/** 音量调节 */
@property (nonatomic, strong) UISlider *volumeSlider;
/** 系统音量 */
@property (nonatomic, assign) CGFloat sysVolume;
/** 亮度调节 */
@property (nonatomic, assign) CGFloat brightness;
/** 进度调节 */
@property (nonatomic, assign) CGFloat currentTime;
/** 定时器 */
@property (nonatomic, strong) NSTimer *timer;

@property (nonatomic, strong) NSTimer *timer1;




@end

#define kFullScreenFrame CGRectMake(0 , 0, kVideoScreenH, kVideoScreenW)


static const NSInteger maxSecondsForBottom = 5.f;

@implementation HJVideoPlayerController

#pragma mark - 生命周期

//- (void)dealloc
//{
//    [self.aliPlayer releasePlayer];
//}

- (instancetype)initWithFrame:(CGRect)frame{
    self = [super init];
    if (self) {
        self.originFrame = frame;
    }
    return self;
}

#pragma mark - 播放器初始化
-(AliyunVodPlayer *)aliPlayer{
    if (!_aliPlayer) {
        _aliPlayer = [[AliyunVodPlayer alloc] init];
        _aliPlayer.delegate = self;
        [_aliPlayer setAutoPlay:YES];
        _aliPlayer.quality=  0;
        _aliPlayer.circlePlay = NO;
        _aliPlayer.displayMode = AliyunVodPlayerDisplayModeFitWithCropping;
        NSArray *pathArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *docDir = [pathArray objectAtIndex:0];
        //maxsize MB    maxDuration 秒
        [_aliPlayer setPlayingCache:YES saveDir:docDir maxSize:3000 maxDuration:100000];
    }
    return _aliPlayer;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
//    if (self.aliPlayer) {
//        [self.aliPlayer stop];
//    }
//
//    [self.aliPlayer prepareWithVid:@"a66696f373844fa681a819ba5311d5d6"
//                       accessKeyId:AccessKeyID
//                   accessKeySecret:AccessKeySecret
//                     securityToken:SecurityToken];

    
    [self setupUI];
    [self initW];

    [self addTapGesture];
    
    [self.bottomView.bufferSlider.progressSlider addTarget:self action:@selector(timeProgress:) forControlEvents:UIControlEventValueChanged];
    [self.bottomView.bufferSlider.progressSlider addTarget:self action:@selector(endProgress:) forControlEvents:UIControlEventTouchUpInside];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:NO];
    //允许屏幕旋转
    AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    if (self.configModel.onlyFullScreen) {
        delegate.orientationMask = UIInterfaceOrientationMaskLandscape;
        [UIDevice rotateToOrientation:UIInterfaceOrientationLandscapeRight];
        [self changeFullScreen:YES];
    }else{
        delegate.orientationMask = UIInterfaceOrientationMaskAllButUpsideDown;
    }
    //禁用侧滑手势方法
    self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    //开启屏幕长亮
    [UIApplication sharedApplication].idleTimerDisabled = YES;
    
    mProgressCanUpdate = YES;

}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:NO];
    [self cancelTimer];
    [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:NO];
    //关闭屏幕旋转
    AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    delegate.orientationMask = UIInterfaceOrientationMaskPortrait;
    [UIDevice rotateToOrientation:UIInterfaceOrientationPortrait];
    //关闭屏幕长亮
    [UIApplication sharedApplication].idleTimerDisabled = NO;
    //禁用侧滑手势方法
    self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    //暂停播放
    [self pause];
}




- (void)initW
{
    self.secondsForBottom = maxSecondsForBottom;
    self.currentTime      = 0;
    
    //获取系统音量滚动条
    MPVolumeView *volumeView = [[MPVolumeView alloc]init];
    for (UIView *tmpView in volumeView.subviews) {
        if ([[tmpView.class description] isEqualToString:@"MPVolumeSlider"]) {
            self.volumeSlider = (UISlider *)tmpView;
        }
    }
}


- (void)clearInfo{
    
    if (_bottomView) {
        [self.bottomView setProgress:0];
        [self.bottomView setMaximumValue:0];
        [self.bottomView setBufferValue:0];
    }
    
    self.playStatus = videoPlayer_unknown;
    self.currentTime = 0;
}

- (UIView *)playerView{
    if (!_playerView) {
        _playerView = [[UIView alloc] init];
    }
    return  _playerView;
}

#pragma mark - About UI
- (void)setupUI
{
    // 设置self
    if (!self.configModel.onlyFullScreen) {
        [self.view setFrame:self.originFrame];
    }else{
        [self.view setFrame:CGRectMake(0, 0,kVideoScreenW, kVideoScreenH)];
    }
    
    [self.view setClipsToBounds:YES];
    
    // 设置player
    self.playerView = self.aliPlayer.playerView;
//    [self.playerView setFrame:self.view.frame];
    [self.playerView setFrame:self.view.bounds];
//    self.playerView.frame= CGRectMake(-3, 0, self.view.bounds.size.width, self.view.bounds.size.height);

//    [self.playerView setBackgroundColor:[UIColor redColor]];
//    [self.playerView setImage:imgVideoBackImg];
//    [self.playerView setUserInteractionEnabled:YES];
    [self.view addSubview:self.playerView];
    
    //设置遮罩层
    self.maskView = [[HJVideoMaskView alloc] initWithFrame:self.playerView.bounds];
    self.maskView.backgroundColor = kVideoMaskViewBGColor;

    WS(weakSelf);
    self.maskView.playBlock = ^(BOOL isPlay) {
        if (isPlay) {
            [weakSelf play];
        }else{
            [weakSelf pause];
        }

        [weakSelf resetTimer];
    };

    __weak HJVideoMaskView * weakMaskView = self.maskView;
    self.maskView.replayBlock = ^{
        weakMaskView.maskViewStatus = VideoMaskViewStatus_showPlayBtn;
        [weakSelf resetTimer];
    };

    self.maskView.playFailedClickBlock = ^{
        [weakSelf setUrl:weakSelf.url];
    };
    [self.playerView addSubview:self.maskView];



    // 设置topView
    self.topView.frame = CGRectMake(0, 0, self.view.frame.size.width, kBottomBarHalfHeight);
    [self.view addSubview:self.topView];

    // 设置BottomView
    self.bottomView.frame = CGRectMake(0, CGRectGetHeight(self.view.frame) - kBottomBarHalfHeight, self.view.frame.size.width, kBottomBarHalfHeight);
    self.bottomView.configModel = self.configModel;
    [self.view addSubview:self.bottomView];
}


- (void)changeFullScreen:(BOOL)changeFull{
    
    self.isFullScreen = changeFull;
    
    [self.view.superview bringSubviewToFront:self.view];
    
    [UIView animateWithDuration:kDefaultAnimationDuration animations:^{
        if (changeFull) {
            self.view.frame = kVideoFullFrame;
        }else{
            self.view.frame = self.originFrame;
        }
        
        self.playerView.frame = self.view.bounds;
        self.maskView.frame = self.playerView.bounds;
        
        // 发送屏幕改变通知
        [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationChangeScreen object:@(changeFull)];
    }];
}
#pragma mark - 底部栏显示/隐藏

- (void)addTapGesture
{
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(startTimer)];
    [self.view addGestureRecognizer:tap];
    [self startTimer];
}

- (void)showBottomAction
{
    if (!self.bottomView.onlySlider) {
        [self.bottomView hide];
    }else{
        [self.bottomView show];
    }
}


- (void)startTimer
{
    //看是否正在计时，若是则结束计时 否则开始计时
    if (self.timer) {
    
        [self cancelTimerAndHideViews];
        
    }else{
        [self setSecondsForBottom:maxSecondsForBottom];
        [self hideTopView:NO];
        [self.bottomView show];
        
        [self.maskView show];
        self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self
                                                    selector:@selector(timerAction)
                                                    userInfo:nil
                                                     repeats:YES];
    }
}


- (void)resetTimer{
    
    if ([self.timer isValid]) {
        self.secondsForBottom = 5.f;
    }else{
        [self startTimer];
    }
}


- (void)cancelTimerAndHideViews{
    
    [self hideSomeViews];
    
    [self cancelTimer];
}


- (void)cancelTimer{

    
    if (!self.timer) {
        return;
    }
    
    [self.timer invalidate];
    self.timer = nil;
}

- (void)hideSomeViews{
    
    //顶部视图隐藏
    if (self.isFullScreen) {
        [self hideTopView:YES];
    }
    
    //底部视图隐藏
    [self.bottomView hide];
    
    //中间内容隐藏 暂停 播放失败 和播放结束 无需隐藏显示内容
    if(self.playStatus != videoPlayer_readyToPlay &&
       self.maskView.maskViewStatus != VideoMaskViewStatus_showLoading &&
       self.maskView.maskViewStatus != VideoMaskViewStatus_showPlayFailed &&
       !self.maskView.isPausing){
        [self.maskView hide];
    }

    self.secondsForBottom = 0;
}


- (void)hideTopView:(BOOL)hide{

    self.topView.hidden = hide;
    //状态栏显示跟随topView
    [[UIApplication sharedApplication] setStatusBarHidden:hide withAnimation:NO];
}


- (void)timerAction{
    
        self.secondsForBottom --;
        NSLog(@"隐藏底部栏:%zd",self.secondsForBottom);
        if (self.secondsForBottom <= 0) {
            [self cancelTimerAndHideViews];
        }
}



//
//- (void)addObservers{
//
//    [[NSNotificationCenter defaultCenter] addObserver:self
//                                             selector:@selector(applicationDidEnterBackground)
//                                                 name:UIApplicationDidEnterBackgroundNotification
//                                               object:nil];
//
//    [[NSNotificationCenter defaultCenter] addObserver:self
//                                             selector:@selector(applicationWillEnterForeground)
//                                                 name:UIApplicationWillEnterForegroundNotification
//                                               object:nil];
//
//}


#pragma mark - 公开方法
- (void)play{
    

//    [self setPlayStatus:videoPlayer_playing];
//    [self.maskView setPlayStatus:YES];
//    [self.aliPlayer resume];
    
    [self setPlayStatus:videoPlayer_playing];
    [self.maskView setPlayStatus:YES];
    if (self.aliPlayer.playerState == AliyunVodPlayerStateFinish) {
        [self.aliPlayer replay];

    }
    else {

            [self.aliPlayer resume];
    }

}

- (void)pause{
    
    [self setPlayStatus:videoPlayer_pause];
    [self.maskView setPlayStatus:NO];
    [self.aliPlayer pause];

}


- (void)pausePlayAndBuffer{

    [self pause];
    
}


//#pragma mark - 事件响应
//- (void)applicationDidEnterBackground {
//
//    if (self.playStatus == videoPlayer_playing) {
//        [self pause];
//    }
//}
//
//
//- (void)applicationWillEnterForeground {
//
//    if (self.prePlayStatus == videoPlayer_playing) {
//        [self play];
//    }
//}

//- (void)playOrPauseAction:(UIButton *)sender{
//    sender.selected = !sender.selected;
//    if (sender.selected) {
//        [self play];
//    }else{
//        [self pause];
//    }
//}

- (void)studyRecord {
    
    if (!self.mid3) {
        return;
    }
    
    NSDictionary *dic = @{
                          @"uid":[LoginModel shareLogin].uid,
                          @"token":[LoginModel shareLogin].token,
                          @"username":[LoginModel shareLogin].username,
                          @"cid":self.cid,
                          @"mid":self.mid3,
                          @"playback":self.playback
                          };
    [SVProgressHUD show];
    [AFNHelper post:StudyRecord parameters:dic success:^(id responseObject) {
        
        //        NSLog(@"%@",responseObject);
        if ([responseObject[@"status"] isEqual:@1]) {
            
            //            self.isBuy = responseObject[@"data"][@"is_buy"];
            
            
        }
        [SVProgressHUD showWithStatus:responseObject[@"message"]];
        [SVProgressHUD dismiss];
        
    } faliure:^(id error) {
        
        NSLog(@"请求失败");
        [SVProgressHUD dismiss];
        
    }];
    
}

- (void)recordProgress {
    
    NSDictionary *dic = @{
                          @"uid":[LoginModel shareLogin].uid,
                          @"token":[LoginModel shareLogin].token,
                          @"username":[LoginModel shareLogin].username,
                          @"cid":self.cid,
                          @"mid":self.mid,
//                          @"mid":self.mid3,
                          @"playback":self.playback
                          };
    [SVProgressHUD show];
    [AFNHelper post:RecordProgress parameters:dic success:^(id responseObject) {
        
        //        NSLog(@"%@",responseObject);
        if ([responseObject[@"status"] isEqual:@1]) {
            
//            self.isBuy = responseObject[@"data"][@"is_buy"];

            
        }
        [SVProgressHUD showWithStatus:responseObject[@"message"]];
        [SVProgressHUD dismiss];
        
    } faliure:^(id error) {
        
        NSLog(@"请求失败");
        [SVProgressHUD dismiss];
        
    }];
    
}

// 半屏返回
- (void)popAction{
    
    [self.navigationController popViewControllerAnimated:YES];
    [self.view removeFromSuperview];
    [self removeFromParentViewController];
    
    // 当前播放进度
    self.playback = [NSString stringWithFormat:@"%f",self.aliPlayer.currentTime];
    [self studyRecord];
    
    // 最新进度
    if (self.clickSection == self.currentSection && self.clickPosition == self.currentPosition) {

        if (self.aliPlayer.currentTime > self.playback.floatValue) {
            self.playback = [NSString stringWithFormat:@"%f",self.aliPlayer.currentTime];
            [self recordProgress];

        }

    }

    
    // 测试
//    [self recordProgress];
}
#pragma mark - getters / setters
- (HJVideoTopView *)topView{
    if (!_topView) {
        WS(weakSelf);
        _topView = [[HJVideoTopView alloc]init];
        _topView.backBlock = ^(){
            if (weakSelf.configModel.onlyFullScreen) {//仅支持全屏  直接返回
                weakSelf.view.frame = CGRectZero;
                [weakSelf.navigationController popViewControllerAnimated:YES];
            }else{
                if(weakSelf.isFullScreen){//全屏返回
                    [UIDevice rotateToOrientation:UIInterfaceOrientationPortrait];
                    [weakSelf changeFullScreen:NO];
                }else{//半屏返回操作
                    [weakSelf popAction];
                }
            }
        };
        
//        _topView.showListBlock = ^(BOOL show){
//            
//            
//        };
    }
    return _topView;
}

- (HJVideoBottomView *)bottomView{
    if (!_bottomView) {
        WS(weakSelf);
        _bottomView = [[HJVideoBottomView alloc] init];
        _bottomView.fullScreenBlock = ^(BOOL isFull){
            if(isFull){
                [UIDevice rotateToOrientation:UIInterfaceOrientationLandscapeRight];
            }else{
                [UIDevice rotateToOrientation:UIInterfaceOrientationPortrait];
            }
            [weakSelf changeFullScreen:isFull];
        };
        
        _bottomView.valueChangedBlock = ^(float value) {

        };
    }
    return _bottomView;
}

//- (HJPlayerView *)playerView{
//    if (!_playerView) {
//        _playerView = [[HJPlayerView alloc] init];
//    }
//    return _playerView;
//}


- (void)setUrl:(NSString *)url{
    if (!url) return;
    
    if (![_url isEqualToString:url]) {//若切换URL
        //清除视频标题
        self.videoTitle = @"";
    }
    _url = url;
    
    
    if (self.aliPlayer) {
        [self.aliPlayer stop];
        [self clearInfo];
    }
    
    [self.aliPlayer prepareWithVid:url
                       accessKeyId:AccessKeyID
                   accessKeySecret:AccessKeySecret
                     securityToken:SecurityToken];
    

    self.maskView.maskViewStatus = VideoMaskViewStatus_showLoading;

}

- (void)setVideoTitle:(NSString *)videoTitle{
    _videoTitle = videoTitle;
    self.topView.title = videoTitle;
}

- (void)setPlayStatus:(VideoPlayerStatus)playStatus{
    
    self.prePlayStatus = _playStatus;
    _playStatus = playStatus;
}

- (HJVideoConfigModel *)configModel{
    
    if (!_configModel) {
        _configModel = [[HJVideoConfigModel alloc] init];
        _configModel.autoPlay = YES;//默认设置url自动播放
    }
    return _configModel;
}


- (void)setIsFullScreen:(BOOL)isFullScreen{
    
    if (_isFullScreen != isFullScreen) {
        _isFullScreen = isFullScreen;
        //屏幕切换回调
        if (self.screenChangedBlock) {
            self.screenChangedBlock(isFullScreen);
        }
    }
}

/*
#pragma mark - 触摸事件
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    [super touchesBegan:touches withEvent:event];
    UITouch * touch = [touches anyObject];
    self.startPoint = [touch locationInView:self.view];
    self.sysVolume = self.volumeSlider.value;
    self.brightness = [UIScreen mainScreen].brightness;
    self.currentTime = self.bottomView.progressValue;
}

- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{

    [super touchesMoved:touches withEvent:event];
 
    //状态未知时不可拖动 如（未进入准备状态）
    if(self.playStatus == videoPlayer_unknown ||
       self.playStatus == videoPlayer_playFailed ||
       self.playStatus == videoPlayer_playEnd ||
       self.playStatus == videoPlayer_loading){
        return;
    }
    
    [self setSecondsForBottom:maxSecondsForBottom];
    UITouch * touch = [touches anyObject];
    CGPoint movePoint = [touch locationInView:self.view];
    
    CGFloat subX = movePoint.x - self.startPoint.x;
    CGFloat subY = movePoint.y - self.startPoint.y;
    CGFloat width  = self.view.frame.size.width;
    CGFloat height = self.view.frame.size.height;
    
    BOOL startInLeft = movePoint.x < width/2.f;
    
    
    if (self.moveDirection == MoveDirection_none) {
        if (subX >= 30) {
            self.moveDirection = MoveDirection_right;
        }else if(subX <= -30){
            self.moveDirection = MoveDirection_left;
        }else if (subY >= 30){
            self.moveDirection = MoveDirection_down;
        }else if (subY <= -30){
            self.moveDirection = MoveDirection_up;
        }
    }
    
    if (self.moveDirection == MoveDirection_right || self.moveDirection == MoveDirection_left) {//快进
        CGFloat ratio = subX/width;
        CGFloat offsetSeconds = self.bottomView.maximumValue*ratio;
        CGFloat seekTime = self.currentTime + offsetSeconds;
        [self.maskView.fastForwardView setMaxDuration:self.bottomView.maximumValue];
        self.maskView.maskViewStatus = VideoMaskViewStatus_showFastForward;
        [self.maskView.fastForwardView moveRight:offsetSeconds>0];
        [self.maskView.fastForwardView setProgress:seekTime/self.bottomView.maximumValue];
        [self resetTimer];
        [self.bottomView hide];
    }else if (self.moveDirection == MoveDirection_up || self.moveDirection == MoveDirection_down){
        if (startInLeft) {//上调亮度
            [UIScreen mainScreen].brightness = self.brightness - subY/height;//10;
        }else{//上调音量
            self.volumeSlider.value = self.sysVolume - subY/height;//10;
        }
    }

}

- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    [super touchesEnded:touches withEvent:event];
    if (self.moveDirection == MoveDirection_left || self.moveDirection == MoveDirection_right) {
//        [kVideoPlayerManager seekToTime:self.maskView.fastForwardView.currentDuration];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.05 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            self.playStatus = self.prePlayStatus;
            [self cancelTimerAndHideViews];
        });
    }
    [self setMoveDirection:MoveDirection_none];
    [self setCurrentTime:0];
}
*/

#pragma mark - 屏幕旋转
- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
    //全屏不支持屏幕旋转
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(duration * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if (toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft || toInterfaceOrientation == UIInterfaceOrientationLandscapeRight) {
            //屏幕从竖屏变为横屏时执行
            [self changeFullScreen:YES];
        }else{
            //屏幕从横屏变为竖屏时执行
            [self changeFullScreen:NO];
        }
    });
}

- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
    
    
}

#pragma mark - AliyunVodPlayerManagerDelegate
- (void)vodPlayer:(AliyunVodPlayer *)vodPlayer onEventCallback:(AliyunVodPlayerEvent)event{
    //清晰度,beginLoading时 getAliyunMediaInfo 已经获取到当前所选择清晰度视频信息。
    if (event == AliyunVodPlayerEventBeginLoading) {//视频开始载入时触发


        
        AliyunVodPlayerVideo *videoModel = [self.aliPlayer getAliyunMediaInfo];
        
        if (videoModel) {
            [self.bottomView setMaximumValue:videoModel.duration];
        }else{
            [self.bottomView setMaximumValue:self.aliPlayer.duration];
        }
        
//        [_qualitysAry removeAllObjects];
//        [_qualityControl removeAllSegments];
//        for (NSString* quality in videoModel.allSupportQualitys) {
//            NSString* qualityDescription = [self videoQualityToString:quality];
//            int index = (int)[_qualityControl numberOfSegments];
//            [_qualityControl insertSegmentWithTitle:qualityDescription atIndex:index animated:TRUE];
//            if ([quality intValue] == (int)videoModel.videoQuality) {
//                [_qualityControl setSelectedSegmentIndex:[_qualityControl numberOfSegments]-1];
//            }
//            [_qualitysAry addObject:quality];
//        }
//        NSLog(@"vodplayer --- %d",vodPlayer.quality);
    }
    
    //封装播放器时，按需求考虑添加timer
    if (event == AliyunVodPlayerEventPrepareDone) {//播放准备完成时触发
        
        // 最新进度
        if (self.mid2.integerValue == self.mid3.integerValue) {
            
            [self.bottomView setProgress:self.playback.floatValue];
            [ self.aliPlayer seekToTime:self.playback.floatValue];
            
        }
        else {
            self.mid2 = nil;
            [self.bottomView setProgress:0];
            [ self.aliPlayer seekToTime:0];
        }


        
        if(self.maskView.maskViewStatus != VideoMaskViewStatus_showPlayBtn) {
            self.maskView.maskViewStatus = VideoMaskViewStatus_showPlayBtn;
            [self.maskView setPlayStatus:YES];

            [self hideSomeViews];
        };


        [self.timer1 invalidate];
        self.timer1 = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerRun:) userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop] addTimer:self.timer1 forMode:NSDefaultRunLoopMode];
    }
    
    //@"开始播放";
    if (event == AliyunVodPlayerEventPlay) {
        

        
    }
    
//    ////@"视频跳转seek结束";
//    if (event == AliyunVodPlayerEventSeekDone) {
//
//    }
    
    //@"播放视频完成";
    if (event == AliyunVodPlayerEventFinish) {
        
        NSLog(@"播放视频完成");
        
        [self setPlayStatus:videoPlayer_pause];
        [self.maskView setPlayStatus:NO];
        self.playback = @"0";
        
        
        // 当前播放进度
        self.playback = [NSString stringWithFormat:@"%f",self.aliPlayer.currentTime];
        [self studyRecord];
        
        // 最新进度
        if (self.clickSection == self.currentSection && self.clickPosition == self.currentPosition) {
            
            // 章model
            YYEChapterModel *cModel = _datas[self.currentSection];
            
            NSInteger currentPosition = 0;
            NSInteger currentSection = 0;
            
            if (self.currentPosition < cModel.children.count-1) {
                
                // 本章的下一节
                currentSection = self.currentSection;
                currentPosition = self.currentPosition +1;
                YYELittleChapterModel *lModel = cModel.children[currentPosition];
                self.mid = lModel.id;
                
            }
            else {
                
                
                // 下一章的第一节
                if (self.currentSection < _datas.count-1) {
                    
                    currentSection = self.currentSection +1;
                    currentPosition = 0;
                    YYEChapterModel *cModel = _datas[currentSection];
                    YYELittleChapterModel *lModel = cModel.children[0];
                    self.mid = lModel.id;
                }
                
            }
            
            [self recordProgress];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"kIndexNotification" object:nil userInfo:@{@"currentSection":@(currentSection),@"currentPosition":@(currentPosition)}];
        }
        
        

    }
    
//    //增加log展示内容
//    [self.showMessageView addTextString:[self getMessageWithevent:event errorMsg:nil] ];
}

//播放出错时触发，通过errorModel可以查看错误码、错误信息、视频ID、视频地址和requestId。
- (void)vodPlayer:(AliyunVodPlayer *)vodPlayer playBackErrorModel:(ALPlayerVideoErrorModel *)errorModel{
    mProgressCanUpdate = YES;
    self.maskView.maskViewStatus = VideoMaskViewStatus_showPlayFailed;

//    NSString* errDescription = [self getMessageWithevent:errorModel.errorCode errorMsg:errorModel.errorMsg];
//    [self.showMessageView addTextString:errDescription];
//    self.tempErrorModel = errorModel;
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"error", nil) message:@"errorModel.errorMsg" delegate:nil cancelButtonTitle:NSLocalizedString(@"ok_button1", nil) otherButtonTitles:nil];
    [alert show];
}

//将要切换清晰度时触发
- (void)vodPlayer:(AliyunVodPlayer*)vodPlayer willSwitchToQuality:(AliyunVodPlayerVideoQuality)quality{
    mProgressCanUpdate = NO;
}

//清晰度切换完成后触发
- (void)vodPlayer:(AliyunVodPlayer *)vodPlayer didSwitchToQuality:(AliyunVodPlayerVideoQuality)quality{
    [self.bottomView setMaximumValue:vodPlayer.duration];
    mProgressCanUpdate = YES;
    NSLog(@"vodplayer --- %d",quality);
    
//    self.playBtn.enabled = NO;
//    self.stopBtn.enabled = YES;
//    self.pauseBtn.enabled = YES;
//    self.resumeBtn.enabled = NO;
    
//    [self.aliPlayer setRenderRotate:self.rotatedSegment.selectedSegmentIndex*90];
//    [self.aliPlayer setRenderMirrorMode:self.mirrorSegment.selectedSegmentIndex];
    
}

//清晰度切换失败触发
- (void)vodPlayer:(AliyunVodPlayer*)vodPlayer failSwitchToQuality:(AliyunVodPlayerVideoQuality)quality{
}

////开启循环播放功能，开始循环播放时接收此事件。
//- (void)onCircleStartWithVodPlayer:(AliyunVodPlayer *)vodPlayer{
//}


#pragma mark - seek
- (void)timeProgress:(UISlider *)sender {
    if (self.aliPlayer && (self.aliPlayer.playerState == AliyunVodPlayerStateLoading || self.aliPlayer.playerState == AliyunVodPlayerStatePause ||
                           self.aliPlayer.playerState == AliyunVodPlayerStatePlay)) {
        mProgressCanUpdate = NO;
//        [ self.aliPlayer seekToTime:sender.value * self.aliPlayer.duration];
//        [ self.aliPlayer seekToTime:sender.value];

        
//        if (sender.value < self.aliPlayer.currentTime) {
//
//            [ self.aliPlayer seekToTime:sender.value];
//
//        }
//        else {
//            [ self.aliPlayer seekToTime:self.aliPlayer.currentTime];
//
//        }
        
//        NSLog(@"value-------%f",sender.value);


    }
}

// 快进控制
- (void)endProgress:(UISlider *)sender {
    
    NSLog(@"sender.value--------%f",sender.value);
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        mProgressCanUpdate = YES;

    });
    
    if (self.clickSection == self.currentSection && self.clickPosition == self.currentPosition) {
        
        if (sender.value > self.aliPlayer.currentTime) {
            
            [self.view makeToast:@"未看过的不可播放"];
            //            NSLog(@"未看过的不可播放");
            
            [ self.aliPlayer seekToTime:self.aliPlayer.currentTime];
            [self.bottomView setProgress:self.aliPlayer.currentTime];
            
        }
        else {
            [ self.aliPlayer seekToTime:sender.value];
            
        }
    }
    else {
        [ self.aliPlayer seekToTime:sender.value];

    }
    
//    [ self.aliPlayer seekToTime:sender.value];

}

#pragma mark - timerRun
- (void)timerRun:(NSTimer *)sender{
//    //音柱数据
//    [self.aliPlayer getAudioData:^(NSData *data) {
//        //        NSLog(@"data---%lu",(unsigned long)data.length);
//    }];
    
    //缓存文件大小， 路径要与开始设置相同。需要测试时打开
//    [self fileSize];
    
    if (self.aliPlayer && mProgressCanUpdate == YES) {
//        self.leftTimeLabel.text = [self getMMSSFromSS:[NSString stringWithFormat:@"%.f",self.aliPlayer.currentTime]];
//        [self.timeProgress setValue:self.aliPlayer.currentTime/self.aliPlayer.duration animated:YES];
//        [self.progressView setProgress:self.aliPlayer.loadedTime/self.aliPlayer.duration];
        
//        [self.bottomView setBufferValue:self.aliPlayer.loadedTime];
//        [self.bottomView setProgress:self.aliPlayer.currentTime/self.aliPlayer.duration];
        [self.bottomView setProgress:self.aliPlayer.currentTime];
        [self.bottomView setMaximumValue:self.aliPlayer.duration];
        
        NSLog(@"currentTime-------%f",self.aliPlayer.currentTime);

    }
}

#pragma mark - 缓存文件大小
-(void)fileSize{
    NSArray *pathArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *docDir = [pathArray objectAtIndex:0];
    NSString *filePath = docDir;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if([fileManager fileExistsAtPath:docDir isDirectory:nil]){
        NSArray *subpaths = [fileManager contentsOfDirectoryAtPath:filePath error:nil];
        for (NSString *subpath in subpaths) {
            
            NSString *fullSubpath = [filePath stringByAppendingPathComponent:subpath];
            if ([subpath hasSuffix:@".mp4"]) {
                long long fileSize =  [fileManager attributesOfItemAtPath:fullSubpath error:nil].fileSize;
                NSLog(@"fileSie ---- %lld",fileSize);
            }
        }
    }
}


@end
